'use strict';
let mongoose = require('mongoose');

let LeaveMessage = new mongoose.Schema({
    from : String,
    content : String
}, {versionKey: false});

let schema = new mongoose.Schema({
    friends :[String], //好友
    weFriends :[String], //微信好友
    enemys : [String],
    applys : [String],  //向我申请的关系
    love :{
        type : Number,
        default : 0,
        index:true
    },  //我的爱心数量
    leaveMessage : {
        type : [LeaveMessage],
        default : []
    }
});

schema.statics = {

};

schema.methods = {
    async _addSocial(selfUser,array,_id,key){
        if(array.indexOf(_id)>=0){//已经是当前关系
            return;
        }
        let GameUserModel = mongoose.models['GameUser']
        let gameUser = await GameUserModel.getOne({_id:_id})
        this[key].push(_id);
        await selfUser.save();
        if(gameUser.social[key].indexOf(selfUser._id)>=0){
            return;
        }
        gameUser.social[key].push(selfUser._id);
        await gameUser.save();
    },
    // async _addFriend(selfUser,_id){
    //     this._addSocial(selfUser,this.friends,_id,'friend');
    // },
    async _addWechatFriend(selfUser,_id){
        if(this.friends.indexOf(_id)>=0){
            // throw new Error('已经是好友')
            return
        }
        let GameUserModel = mongoose.models['GameUser']
        let gameUser = await GameUserModel.getOne({_id:_id})
        this.friends.push(_id);
        await this.save();
        if(gameUser.social.friends.indexOf(selfUser._id)>=0){
            return;
        }
        gameUser.social.friends.push(selfUser._id);
        await gameUser.save();
    },
    async friendList(options){
        let friends = await this._getUsersInfo(this.friends);
        await this._getLastInfo(friends,options.self.id)
        // console.log('friendList:',friends)
        return friends
    },
    async weFriendList(options){
        let friends = await this._getUsersInfo(this.weFriends);
        // await this._getLastInfo(friends,options.self.id)
        // console.log('friendList:',friends)
        return friends
    },
    _getEaseInfo(users){
        let datas = [];
        for(let i=0; i<users.length; i++){
            let user = users[i];
            datas.push({
                _id:user._id,
                id:user.id,
                sex:user.sex,
                headImgUrl:user.headImgUrl,
                level:user.ppt.level,
                nickname:user.nickname
            })
        }
        return datas;
    },
    async _getUsersInfo(arr){
        let GameUserModel = mongoose.models['GameUser']
        let users = await GameUserModel.find({_id:{$in:arr}});
        return this._getEaseInfo(users);
    }, 
    async _getLastInfo(friends,selfId){
        let ChatModel = mongoose.models['Chat']

        for(let i=0; i<friends.length; i++){
            let id = friends[i].id;
            let channel = 'private_'+Math.min(id,selfId)+'_'+Math.max(id,selfId);
            let chat = await ChatModel.findOne({channel:channel});
            if(chat && chat.messages.length){
                friends[i].lastMsg = chat.messages[chat.messages.length-1];
                friends[i].lastGetTick = chat.lastGetTick
            }
        }
    },
    async applyFriend(options){
        let _id = options.uid;
        if(_id == options.self._id){
            return
        }
        if(this.enemys.findIndex(item=>{return item==_id})>=0){
            throw  new Error('仇人状态不允许添加好友')
        }
        if(this.friends.findIndex(item=>{return item==_id})>=0){
            throw new Error('已经是游戏好友')
        }
        let GameUserModel = mongoose.models['GameUser']
        let gameUser = await GameUserModel.getOne({_id:_id})
        if(gameUser.social.applys.indexOf(_id)>=0){
            throw  new Error('已经申请过了')
        }
        if(gameUser.social.friends.length >= 50){
            throw  new Error('对方好友已满')
        }
        let idx = gameUser.social.applys.findIndex(item=>{return item == options.self._id.toString()});
        if(idx<0){
            gameUser.social.applys.push(options.self._id)
        }
        await gameUser.save();
    },
    async applyList(options){
        return await this._getUsersInfo(this.applys);
    },
    _deleteArrayObject(arr,obj){
        for(let i=0; i<arr.length; i++){
            if(arr[i] == obj){
                arr.splice(i,1);
                return;
            }
        }
    },
    async friendBroke(options){
        let GameUserModel = mongoose.models['GameUser']
        let idx = this.friends.findIndex(item=>{return item == options.uid})
        if(idx < 0){
            throw new Error('对方不是您的好友')
        }
        this.friends.splice(idx,1);
        let gameUser = await GameUserModel.findOne({_id:options.uid})
        if(!gameUser ){
            await options.self.save();
            throw new Error('查无此人')
        }
        let dx = gameUser.social.friends.findIndex(item=>{return item == options.self._id.toString()});
        if(dx >=0){
            gameUser.social.friends.splice(dx,1);
        }
        await options.self.save();
        await gameUser.save();
    },
    async applyResult(options){
        let _id = options.uid;
        let GameUserModel = mongoose.models['GameUser']
        let idx = this.applys.indexOf(_id);
        if(idx <0 ) throw new Error('没有这条申请对象')
        this.applys.splice(idx,1);
        this.friends.push(_id);
        await options.self.save();
        if(options.code != 1){
            return;
        }

        let gameUser = await GameUserModel.getOne({_id:options.uid})
        idx = gameUser.social.friends.indexOf(options.self._id)
        if(idx >=0 ){
            throw new Error('你已经是对方的好友')
        }
        gameUser.social.friends.push(options.self._id);
        await gameUser.save();
    },

    async sendLeave(options){ //添加留言
        if(!options.self.bag.getCount(202)){
            throw new Error('比心数量不足')
        }
        let GameUserModel = mongoose.models['GameUser']
        let gameUser = await GameUserModel.getOne({_id:options.uid});
        gameUser.social.leaveMessage.push({
            from : options.self._id,
            content : options.content
        })
        if(gameUser.social.leaveMessage.length > 100){
            gameUser.social.leaveMessage.splice(0,gameUser.social.leaveMessage.length-100)
        }
        await gameUser.save();
        options.self.bag.reduceItem(202,1);
        await options.self.save();
    },

    async fateList(options){
        let GameUserModel = mongoose.models['GameUser']
        let condition = {'social.love':{$lte:1}}
        options.condition && (condition.sex =options.condition)
        let users = await GameUserModel.find(condition).limit(20);
        console.log('users:',condition)
        let us =[];
        while(us.length < 3 && users.length > 0){
            let idx = Math.floor(Math.random() * users.length);
            us.push(users[idx]);
            users.splice(idx,1);
        }
        let resultUsers = [];
        for(let i=0; i<us.length; i++){
            let user = us[i];
            resultUsers.push({
                _id:user._id,
                id:user.id,
                sex:user.sex,
                love:user.social.love,
                latitude:user.latitude,
                longitude:user.longitude,
                headImgUrl:user.headImgUrl,
                address:user.address,
                level:user.ppt.level,
                nickname:user.nickname
            })
        }
        return resultUsers;
    },

    async fateInfo(options){
        let GameUserModel = mongoose.models['GameUser']
        let gameUser = await GameUserModel.getOne({_id:options.uid});
        return {leaveMessage: gameUser.social.leaveMessage,bag:options.self.bag};
    },

    async giveLove(options){
        if(options.self.bag.getCount(202)<=0){
            throw new Error('拥有的比心数量不足')
        }
        let GameUserModel = mongoose.models['GameUser']
        let gameUser = await GameUserModel.getOne({_id:options.uid});
        gameUser.social.love++;
        options.self.bag.reduceItem(202,1);
        await gameUser.save();
        await options.self.save();
    },

    getGreatCircleDistance(lat1,lng1,lat2,lng2){
        function getRad(d){
            return d*Math.PI/180.0;
        }
        let radLat1 = getRad(lat1);
        let radLat2 = getRad(lat2);

        let a = radLat1 - radLat2;
        let b = getRad(lng1) - getRad(lng2);

        let s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) + Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s*6378137.0;
        // s = Math.round(s*10000)/10000;
        return Math.round(s);
    },

    async nearList(options){
        let nearDst = 0.1 * 3;
        let gameUser = options.self;
        if(gameUser.location == 999 && gameUser.latitude == 999){
            throw new Error('未获得授权')
        }
        let s_id = options.self._id;
        let s_latitude = options.self.latitude;
        let s_longitude = options.self.longitude;
        let friendsArr = [];
        for (let i = 0; i < options.self.social.friends.length; i++) {
            friendsArr.push(mongoose.Types.ObjectId(options.self.social.friends[i]));
        }
        let conditions = {
            longitude: {$gte: s_longitude - nearDst, $lte: s_longitude + nearDst},
            latitude: {$gte: s_latitude - nearDst, $lte: s_latitude + nearDst},
            _id: {$ne: s_id, $nin: friendsArr}
        }
        options.condition != undefined && parseInt(options.condition)!=0 && (conditions.sex =options.condition)
        let GameUserModel = mongoose.models['GameUser']
        let nearUsers = await GameUserModel.find(conditions).limit(20);
        console.log('nearUsers',nearUsers.length)
        nearUsers.sort(function(a,b){
            return Math.random() - 0.5
        })
        let users = nearUsers.slice(0,Math.min(6,nearUsers.length))
        let resultUsers = [];
        for(let i=0; i<users.length; i++){
            let user = users[i];
            resultUsers.push({
                _id:user._id,
                id:user.id,
                sex:user.sex,
                love:user.social.love,
                latitude:user.latitude,
                longitude:user.longitude,
                headImgUrl:user.headImgUrl,
                level:user.ppt.level,
                nickname:user.nickname
            })
        }
        return resultUsers;
    },

    async getHint(options){
        let selfId = options.self.id;
        let GameUserModel = mongoose.models['GameUser']
        let ChatModel = mongoose.models['Chat']
        let now = Date.now();
        let obj = {friend : 0,apply:0};

        let i=0;
        while(i<this.friends.length){
            let user = await GameUserModel.findOne({_id:this.friends[i]})
            if(user){
                i++
                let channel = 'private_'+Math.min(user.id,selfId)+'_'+Math.max(user.id,selfId);
                let tickIdx = user.id>selfId ? 0: 1
                let chat = await ChatModel.findOne({channel:channel});
                for(let j=0; chat&&j<chat.messages.length; j++){
                    if(chat.messages[j].time > chat.lastGetTick[tickIdx]){
                        obj.friend++
                    }
                }
            } else {
                this.friends.splice(i,1);
            }
        }
        // i=0;
        // while(i<this.weFriends.length){
        //     let user = await GameUserModel.findOne({_id:this.weFriends[i]})
        //     if(user){
        //         i++
        //         let channel = 'private_'+Math.min(user.id,selfId)+'_'+Math.max(user.id,selfId);
        //         let tickIdx = user.id>selfId ? 0: 1
        //         let chat = await ChatModel.findOne({channel:channel});
        //         for(let j=0; chat&&j<chat.messages.length; j++){
        //             if(chat.messages[j].time > chat.lastGetTick[tickIdx]){
        //                 obj.weFriend++
        //             }
        //         }
        //     } else {
        //         this.weFriends.splice(i,1);
        //     }
        // }

        obj.apply = this.applys.length
        return obj;
    }
}

module.exports = schema;